package smallChanges.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class SCLogger
{
	private static Logger logger;
	private static Logger fileLogger;
	public static final String LOGGER=SCLogger.class.getName();
	public static final String FILE_LOGGER=LOGGER+".FileLogger";
	public static final String ERROR_LOGGER=LOGGER+".ErrorLogger";
	
	public static Logger getLogger() 
	{
		if (logger!=null)
			return logger;
		try {
			logger=createLog();
			
		} catch (IOException e) {
			System.err.println("Unable to configure logger: " +e);
		}
		return logger;
	}
	
	/**
	 * Converts the full stack trace of an exception into a String suitable
	 * for printing to a logger.
	 * @param e The exception
	 * @return The full stack trace of an exception converted into a String suitable
	 * for printing to a logger.
	 */
	public static String toString(Exception e) {
		StringWriter sw=new StringWriter();
		PrintWriter writer=new PrintWriter(sw);
		e.printStackTrace(writer);
		writer.close();
		return sw.getBuffer().toString();
	}
	
	public static Logger getFileLogger() 
	{
		if (fileLogger!=null)
			return fileLogger;
		try {
			if (logger==null)
				logger=createLog();
			fileLogger=Logger.getLogger(FILE_LOGGER);
			return fileLogger;
			
		} catch (IOException e) {
			System.err.println("Unable to configure file logger: " +e);
		}
		return fileLogger;
	}
	
	private static Logger createLog()
	throws IOException
	{
		String configResource="smallChanges/util/log4j.properties";

		Properties log4jProperties = new Properties();
		InputStream in = SCLogger.class.getClassLoader().getResourceAsStream(configResource);
		if (in == null)
			throw new IOException("Could not read resource " + configResource);
		try {
			log4jProperties.load(in);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				// Ignore
			}
		}

		PropertyConfigurator.configure(log4jProperties);

		Logger logger = Logger.getLogger(SCLogger.class.getName());

		return logger;
	}
}
